package com.touchalachs.game;

import java.util.Locale;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.MotionEvent;

import com.touchalachs.core.StringTool;
import com.touchalachs.core.TimeUtil;
import com.touchalachs.core.ui.BasicUIElement;
import com.touchalachs.core.ui.Button;
import com.touchalachs.core.ui.ButtonListener;
import com.touchalachs.core.ui.Label;
import com.touchalachs.core.ui.TextArea;
import com.touchalachs.core.ui.TippableBasicUIElement;

public class StatsPopup extends BasicUIElement implements ButtonListener{

	
	private final Calculator calc;
	private final Label titleLabel;
	private final Label logoLabel;
	private final TextArea statsTextArea;
	private final Button resetButton;
	private volatile boolean visible;
	
	public StatsPopup(Point screenSize, Calculator calc) {
		super(0, 50, 100, 50, screenSize);
		this.calc = calc;
		titleLabel = new Label(5, 51, 90, 8, Res.STATS, screenSize);
		titleLabel.setTextSize(40);
		logoLabel = new Label(75, 95, 25, 3, "(c) hotfix 2013", screenSize);
		logoLabel.setTextSize(15);
		logoLabel.setTextColor(Color.rgb(255, 64, 64));
		statsTextArea = new TextArea(5, 59, 90, 10, "", screenSize);
		statsTextArea.setTextSize(24);
		resetButton = new Button(70, 52, 20, 5, Res.RESET, screenSize, this);
		visible = false;
	}

	public void show() {
		updateText();
		visible = true;
	}

	private void updateText() {
		String duration = TimeUtil.secToTime(calc.getDuration());
		String info = String.format(Locale.getDefault(), Res.STATS_TEXT, 
				duration,
				StringTool.format(calc.getIncome(), 1),
				StringTool.format(calc.getScore()), 
				StringTool.format(calc.getAllTimeScore()));
		statsTextArea.setText(info);
	}

	@Override
	public void draw(Canvas canvas) {
		if (visible){
			updateText();
			Paint p = new Paint();
			p.setARGB(127, 0, 0, 0);
			canvas.drawPaint(p);
			p.setARGB(255, 32, 32, 32);
			canvas.drawRect(getDimension(), p);
			titleLabel.draw(canvas);
			logoLabel.draw(canvas);
			statsTextArea.draw(canvas);
			resetButton.draw(canvas);
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (visible) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				resetButton.onTouchEvent(event);
				visible = false;
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean onTipp(TippableBasicUIElement source) {
		calc.restart();
		return true;
	}

}
